package com.cx.auth.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.cx.auth.common.redis.RedisCache;
import com.cx.auth.constant.RedisKey;
import com.cx.auth.entity.ChatUser;
import com.cx.auth.form.Mail;
import com.cx.auth.form.RegisterBody;
import com.cx.auth.util.Assert;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.UserStatus;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
@Slf4j
public class UserLoginService
{
    @Autowired
    private RedisService redisService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IMailService mailService;

    @Autowired
    private IChatUserService chatUserService;


    /**
     * 登录
     */
    public LoginUser login(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {

            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {

            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {

            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {

            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = null;

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {

            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }
        
        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {

            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {

            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        return userInfo;
    }

    public void logout(String loginName)
    {

    }


    public void register(RegisterBody registerBody){
        String verificationCode = getVerificationCode(registerBody.getEmail());

        if (StringUtils.isEmpty(registerBody.getPassword()))
        {
            throw new ServiceException("密码不能为空");
        }

        Assert.isTrue(registerBody.getCode().equals(verificationCode), "邮箱地址/验证码不正确");



        ChatUser chatUser = new ChatUser();
        chatUser.setEmail(registerBody.getEmail());
        chatUser.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
        if(chatUserService.checkEmailUnique(chatUser))
        {
            chatUser.setEmail(registerBody.getEmail());
            chatUserService.insertUser(chatUser);
            log.info("注册成功");
        }else{
            throw new ServiceException("该用户已经注册");
        }
    }


    public void changePwd(RegisterBody registerBody){
        String verificationCode = getVerificationCode(registerBody.getEmail());

        if (StringUtils.isEmpty(registerBody.getPassword()))
        {
            throw new ServiceException("密码不能为空");
        }

        Assert.isTrue(registerBody.getCode().equals(verificationCode), "邮箱地址/验证码不正确");

        ChatUser chatUser = new ChatUser();
        chatUser.setEmail(registerBody.getEmail());
        chatUser.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
        if(!chatUserService.checkEmailUnique(chatUser))
        {
            chatUser.setEmail(registerBody.getEmail());
            chatUserService.updateUser(chatUser);
            log.info("密码修改成功");
        }else{
            throw new ServiceException("该用户不存在");
        }
    }

    public boolean sendEmail(String email) {
        String key = StrUtil.format(RedisKey.verification_code, email);
        String cacheObj = redisCache.getCacheObject(key);
        if (StringUtils.isNotEmpty(cacheObj))
        {
            throw new ServiceException("邮件仍在2分钟有效期内,请耐心等待");
        }
        String code = RandomUtil.randomNumbers(6);
        log.info("验证码为{}", code);
        Mail mail = new Mail();
        mail.setTo(email);
        mail.setTitle("长新-考试通:用户注册");
        String content = StrUtil.format("您的验证码是:{},验证码在2分钟内有效，请及时验证", code);
        mail.setContent(content);
        boolean result = mailService.send(mail);
        if(result) {
            redisCache.setCacheObject(key, code);
            redisCache.expire(key, 120);
        }
        return result;
    }

    private String getVerificationCode(String email) {
        String key = StrUtil.format(RedisKey.verification_code, email);
        String cacheObj = redisCache.getCacheObject(key);
        return cacheObj == null ? "" : cacheObj;
    }
}
